import { notification } from 'antd';

/**
 * 令牌桶
 * @param total //桶容量
 * @param currentTokenCount //桶当前、初始令牌数
 * @param interval //多久添加一个令牌，单位s
 *
 */
class TokenBucket {
  total: number;
  currentTokenCount: number;
  interval: number;
  timer: any | undefined;
  constructor(total: number, currentTokenCount: number, interval: number) {
    this.total = total;
    this.currentTokenCount = currentTokenCount;
    this.interval = interval;
  }
  start() {
    this.timer = setInterval(() => {
      if (this.currentTokenCount < this.total) {
        this.currentTokenCount++;
      }
    }, this.interval);
  }
  use() {
    this.currentTokenCount--;
    if (this.currentTokenCount <= 0) {
      this.currentTokenCount = 0;
      return new Promise(function (reslove) {
        notification.destroy();
        notification.warning({
          message: '请求过于频繁',
          description: '您的操作过于频繁' + ',' + '请慢一点',
        });
        reslove(true);
      });
    } else {
      return;
    }
  }
  stop() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  }
}

const RequestTokenBucket = new TokenBucket(200, 200, 1000);
export default RequestTokenBucket;
